/*
 * @Author: yuanxiaohu
 * @Date: 2025-06-20 00:26:25
 * @LastEditors: yuanxiaohu
 * @LastEditTime: 2025-06-22 18:04:29
 * @Description: 统计优惠券发放、领取、使用、剩余等信息
 * @FilePath: \wine-trend-hui-18\cloudfunctions\getCoupon\getCouponSummary\index.js
 */
const cloud = require('wx-server-sdk');
cloud.init();
const db = cloud.database();

const couponTypeMap = {
    '1': '折扣券',
    '2': '满减券',
    '3': '积分暴涨券',
    '4': '赠品券',
    '5': '组合券',
    '6': '抽奖券',
    '7': '代理商专属折扣券',
    '8': '采购返利券'
};

function summarizeCoupons(coupons) {
    const summary = {
        total: {},
        issued: {},
        used_expired: {},
        remaining: {}
    };

    // 初始化类型
    Object.values(couponTypeMap).forEach(typeName => {
        summary.total[typeName] = 0;
        summary.issued[typeName] = 0;
        summary.used_expired[typeName] = 0;
        summary.remaining[typeName] = 0;
    });


    coupons.forEach(coupon => {
        const typeName = couponTypeMap[coupon.couponType];

        // 累加基础数据
        summary.total[typeName] += parseInt(coupon.couponTotal || 0);
        summary.issued[typeName] += parseInt(coupon.receivedCount || 0);
        const unclaimed = parseInt(coupon.unclaimedCount || 0); // 未领取
        const isExpired = coupon.effectiveEndTime > Date.now();
        const unUsed = isExpired ? parseInt(coupon.unUsedCount || 0) : 0;// 未使用
        summary.remaining[typeName] += unclaimed + unUsed; // ✅ 使用 unclaimedCount
        // summary.remaining[typeName] += (parseInt(coupon.unclaimedCount) || 0) + (parseInt(coupon.usedCount) || 0);
    });

    // 最后统一计算 used_expired = total - remaining
    Object.keys(summary.total).forEach(typeName => {
        summary.used_expired[typeName] = Math.max(
            (summary.total[typeName] || 0) - (summary.remaining[typeName] || 0),
            0
        );
    });

    return summary;
}

exports.main = async (event, context) => {
    try {
        const coupons = await db.collection('couponList')
            .where({
                _openid: event.data.conditions._openid
            })
            .get();

        const summary = summarizeCoupons(coupons.data);

        return {
            code: 200,
            data: {
                total: summary.total,
                issued: summary.issued,
                used_expired: summary.used_expired,
                remaining: summary.remaining
            }
        };
    } catch (err) {
        console.error(err);
        return {
            code: 500,
            errMsg: err.message
        };
    }
};